package org.example.service.imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.mapper.ClazzMapper;
import org.example.mapper.StudentMapper;
import org.example.pojo.Clazz;
import org.example.pojo.ClazzQueryParm;
import org.example.pojo.PageResult;
import org.example.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImp implements ClazzService {
    @Autowired
    ClazzMapper clazzMapper;
    @Autowired
    StudentMapper studentMapper;
    /**
     * 分页查询
     * @param clazzQueryParm
     * @return
     */
    @Override
    public PageResult<Clazz> findByPage(ClazzQueryParm clazzQueryParm) {
        //设置分页参数
        PageHelper.startPage(clazzQueryParm.getPage(),clazzQueryParm.getPageSize());
        //执行查询
        List<Clazz> clazzList = clazzMapper.findAll(clazzQueryParm);
        //设置状态值
        clazzList.forEach(clazz -> {;

            LocalDate nowTime =LocalDate.now();
            if (clazz.getBeginDate().isAfter(nowTime)){
                clazz.setStatus("未开班");
            }else if (clazz.getEndDate().isBefore(nowTime)){
                clazz.setStatus("已结课");
            }else {
                clazz.setStatus("已开班");
            }
        });
        //解析查询结果，并封装
        Page<Clazz> p = (Page<Clazz>) clazzList;
        return new PageResult<>(p.getTotal(),p.getResult());
    }

    @Override
    public void deleteById(Integer id) {
      if(   studentMapper.findCountByClazzId(id)!= 0){
          throw new RuntimeException("该班级有学生，不能删除");
      }
        clazzMapper.deleteById(id);
    }

    @Override
    public void save(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.save(clazz);
    }

    @Override
    public Clazz findById(Integer id) {
        return clazzMapper.findById(id);
    }


    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    public List<Clazz> findAll() {
       return clazzMapper.findAll(null);
    }
}
